import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, Modal, InputNumber, Upload, Button, Icon, Select, Radio } from 'antd';
import { formatMessage } from 'umi-plugin-react/locale';
import React, { useState, useRef } from 'react';
import { FormComponentProps } from '@ant-design/compatible/es/form';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';

// 导入自定义组件1
import PreviewForm from '@/components/PreviewForm';
import * as BdHelper from '@/utils/BdHelper';
import * as DataHelper from '@/helpers/DataHelper';
import * as TsxHelper from '@/helpers/TsxHelper';

// 常量
const { TextArea } = Input;
const FormItem = Form.Item;

// 定义: 数据表单属性
interface DataFormProps extends FormComponentProps {
  dataModalVisible: boolean;
  isUpdate: boolean
  dataFormValues: any
  common: any
  onSubmit: (fieldsValue: any) => any;
  onCancel: () => void;
}

// 数据表单
const DataForm: React.FC<DataFormProps> = props => {
  // 组件属性
  const { dataModalVisible, form, onSubmit: handleSubmit, onCancel,
    common, isUpdate,dataFormValues } = props;

  // 图片状态
  const [picture, setPicture] = useState<any[]>([]);
  const [uploadChanged, setUploadChanged] = useState<boolean>(false);
  const [previewModelVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [previewImg, setPreviewImg] = useState('');

  const actionRef = useRef<ActionType>();

      // 列定义
      const columns: ProColumns<any>[] = [
        {
            title: '系统变量名',
            dataIndex: 'system_name',
            width: 200,
            render: (value, record) => (
                <Input defaultValue={value?.toString()} style={{width:'100%'}}>
                </Input>
             )
        },
        {
            title: '第三方变量名',
            dataIndex: 'other_name',
            hideInSearch: true,
            width: 200,
            render: (value, record) => (
               <Input defaultValue={value?.toString()} style={{width:'100%'}}>
               </Input>
            )
        },
    ];

  //提交表单
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if(picture.length > 0){
        fieldsValue.file_id   = picture[0].file_id
        fieldsValue.file_url  = picture[0].file_url
      }
      // 如果是更新
      if(isUpdate){
        fieldsValue.id = dataFormValues.id;
      }
      console.log("submit fields ", fieldsValue)

      // 如果更新成功之后，重置表单
      handleSubmit(fieldsValue).then((success:any) => {
        console.log('handleSubmit then success is ', success)
        if(success){
          form.resetFields()
          setPicture([])
        }
      })

    });
  };

  // 设置上传文件值
  const setUploadFile = (fileList:any) => {
    setUploadChanged(true)
    let fileArr = DataHelper.getLastUploadFile(fileList)
    console.log("fileArr is ", fileArr)
    if(fileArr.length > 0){
      setPicture(fileArr)
      setPreviewImg(fileArr[0].file_url)
    }else if(fileArr.length === 0){
      console.log('set picture []')
      setPicture([])
    }
  }

  const modalData = [
    {
        system_name:'系统变量名',
        other_name:'第三方变量名',
    },
    {
        system_name:'系统变量名',
        other_name:'第三方变量名',
    },
    {
        system_name:'系统变量名',
        other_name:'第三方变量名',
    },
  ]

  const getTableData = (params:any) => {
    const listData = {
      data: modalData
    }
    return listData
}

  // 初始化变量
  const token = BdHelper.getBdToken()

  // 编辑时初始化 picture
  const defaultPicture = DataHelper.buildFileByUrl(dataFormValues.file_url)

  // 是否展示图片上传按钮
  const showUploadButton = DataHelper.showUploadBtn(isUpdate, picture, defaultPicture, uploadChanged)

  // 弹出框
  // @ts-ignore
  return <Modal
    destroyOnClose
    title={'模板配置'}
    width={DataHelper.DEFAULT_MODAL_WIDTH}
    visible={dataModalVisible}
    onOk={() => onCancel()}
    onCancel={() => onCancel()}
  >
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'验证码标题'}>
      {form.getFieldDecorator('title', {
        initialValue: isUpdate ? dataFormValues.title : '',
        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
    </FormItem>

    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'验证码内容'}>
      {form.getFieldDecorator('content', {
        initialValue: isUpdate ? dataFormValues.content : '',
        // rules: [],
      })(<TextArea rows={2} placeholder={formatMessage({ id: 'app.base.please_input' })} />)}
    </FormItem>
    <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'模板ID'}>
      {form.getFieldDecorator('id', {
        initialValue: isUpdate ? dataFormValues.id : '',
        // rules: [{ required: true, message: formatMessage({ id: 'app.base.please_input_min_1' }) , min: 1 }],
      })(<Input placeholder={formatMessage({ id: 'app.base.please_input' })}/>)}
    </FormItem>
    <div style={{width:'80%',margin:'10px auto'}}>
    <ProTable<any>
        headerTitle=""
        actionRef={actionRef}
        rowKey="key"
        width={"80%"}
        search={false}
        pagination={false}
        request={params => getTableData(params)}
        columns={columns}
    />
    </div>
    


  </Modal>;
};

export default Form.create<DataFormProps>()(DataForm);
